//index.js
//获取应用实例
var app = getApp()

Page({
  data: {
    totalScoreToPay: 0,
    goodsList: [],
    isNeedLogistics: 0, // 是否需要物流信息
    allGoodsPrice: 0,
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    pingtuanOpenId:null, //拼团的话记录团号
    item_sku_list:[],
    hasNoCoupons: true,
    coupons: [],
    youhuijine: 0, //优惠券金额
    curCoupon: null, //当前选择使用的优惠券
    curCoupon_list: [] //当前选择使用的优惠券list
  },
  onShow: function() {
    var that = this;
    var shopList = [];
    //立即购买下单
    if ("buyNow" == that.data.orderType) {
      var buyNowInfoMem = wx.getStorageSync('buyNowInfo');
      that.data.kjId = buyNowInfoMem.kjId;
      if (buyNowInfoMem && buyNowInfoMem.shopList) {
        shopList = buyNowInfoMem.shopList
      }
    } else {
      //购物车下单
      var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
      that.data.kjId = shopCarInfoMem.kjId;
      if (shopCarInfoMem && shopCarInfoMem.shopList) {
        // shopList = shopCarInfoMem.shopList
        shopList = shopCarInfoMem.shopList.filter(entity => {
          return entity.active;
        });
      }
    }
 
    let i=0
    var allGoodsAndYunPrice=0
    for(i;i<shopList.length;i++){
      let j = shopList[i].price * shopList[i].number;
      allGoodsAndYunPrice+=j
    }  
    that.setData({
      goodsList: shopList,
      allGoodsAndYunPrice: allGoodsAndYunPrice
    });
    that.initShippingAddress();
  },

  onLoad: function(e) {
    this.setData({
      isNeedLogistics: 1,
      orderType: e.orderType,
      pingtuanOpenId: e.pingtuanOpenId,
      pin_tuan_tpl: e.pin_tuan_tpl,
      is_commander: e.is_commander=="1"?true:false
    });
  },
  
  getDistrictId: function(obj, aaa) {
    if (!obj) {
      return "";
    }
    if (!aaa) {
      return "";
    }
    return aaa;
  },

  createOrder: function(e) {
    wx.showLoading();
    var that = this;
    var loginToken = wx.getStorageSync('token') // 用户登录 token
    var remark = ""; // 备注信息
    if (e) {
      remark = e.detail.value.remark; // 备注信息
    }

    var postData = {
      // token: loginToken,
      // goodsJsonStr: that.data.goodsJsonStr,
      // remark: remark
      user_mem:remark,

    };
    if (that.data.kjId) {
      postData.kjid = that.data.kjId
    }
    // if (that.data.pingtuanOpenId) {
    //   that.setData({
    //     ispingtuan: ture,
    //   })
    // }
    if (that.data.isNeedLogistics > 0) {
      if (!that.data.curAddressData) {
        wx.hideLoading();
        wx.showModal({
          title: '错误',
          content: '请先设置您的收货地址！',
          showCancel: false
        })
        return;
      }
      
      //postData.provinceId = that.data.curAddressData.provinceId;
      //postData.cityId = that.data.curAddressData.cityId;
      // if (that.data.curAddressData.districtId) {
      //   postData.districtId = that.data.curAddressData.districtId;
      // }
      // postData.consignee_address = that.data.curAddressData.address;
      //postData.linkMan = that.data.curAddressData.linkMan;
      // postData.consignee_name = that.data.curAddressData.linkman;
      // postData.consignee_mobile = that.data.curAddressData.mobile;
      
      var item_sku_list = [];
      
      for (let i = 0; i < that.data.goodsList.length; i++){
        var item_dis = {};
        let item_sku_valus = that.data.goodsList[i].propertyChildIds;
        let sale_quantity_valus = that.data.goodsList[i].number;
        item_dis.item_sku =item_sku_valus;
        item_dis.sale_quantity =sale_quantity_valus;
        item_sku_list[i]=item_dis;
          //item_sku_list.push(item_sku[item_sku_valus], sale_quantity[sale_quantity_valus]) 
      }
      this.setData({
        item_sku_list:item_sku_list,
      });
      
      postData.item_sku = that.data.goodsList.propertyChildIds,
      postData.sale_quantity = that.data.goodsList.number
      postData.consignee=1
      //postData.mobile = that.data.curAddressData.mobile;
      //postData.code = that.data.curAddressData.code;
      //postData.consignee_telephone = that.data.curAddressData.telephone;
    }
    if (that.data.curCoupon) {
      //postData.couponId = that.data.curCoupon.pk;
      var couponId = that.data.curCoupon.pk;
      that.data.curCoupon_list.push(couponId)
      
    }
    // if (!e) {
    //   postData.calculate = "true";
    // }
    var bulk_purchase={}
    bulk_purchase.bulk_purchase_tpl = that.data.pin_tuan_tpl
    bulk_purchase.group_no = that.data.pingtuanOpenId
    bulk_purchase.item=that.data.goodsList[0].goodsId
    bulk_purchase.group_active=1
    bulk_purchase.is_commander=that.data.is_commander
    that.setData({
      bulk_purchase: bulk_purchase,
    })
    //console.log(that.data.bulk_purchase, that.data.pin_tuan_tpl)
    var order_status = that.data.pin_tuan_tpl!=null ? 12:1
    var ispingtuan = that.data.pin_tuan_tpl != null ? true : false
    //var is_commander = that.data.pingtuanOpenId =="1"? true:false
        wx.request({
          //url: 'https://api.it120.cc/'+ app.globalData.subDomain +'/order/create',
          url: app.globalData.domain + '/wxapp/order/',
          method: 'POST',
          header: {
            //'content-type': 'application/x-www-form-urlencoded', 
            'Authorization': 'JWT ' + wx.getStorageSync('token')
          },
          //data: postData, // 设置请求的 参数
          data: {
            // wxapp_suborder_set: [{
            //   item_sku: 111,
            //   sale_quantity: 1,
            // }],
            // consignee:1
            ispingtuan: ispingtuan,
            wxapp_suborder_set:this.data.item_sku_list,
            consignee: that.data.curAddressData.pk,
            coupon_list: that.data.curCoupon_list,
            user_mem: remark,
            order_status: order_status,
            order_type:ispingtuan == true ? 1:0,
            bulk_purchase: ispingtuan==true? that.data.bulk_purchase:'' ,
          },
          success: (res) => {
            wx.hideLoading();
            
            //if (res.data.code != 0) {
            if (res.statusCode != 200 && res.statusCode != 201){
              wx.showModal({
                title: '错误',
                content: JSON.stringify(res.data),
                //res.data.msg,
                showCancel: false
              })
              return;
            }  
            //console.log(res,"createorder")
            //console.log(that.data.goodsList,"that.data.goodsList")
            if (e && "buyNow" != that.data.orderType) {
              var num = 0;
              var shopCarInfo_list = [];
              var list=[]
              var shopCarInfo_dis = {};
              // 清空购物车数据
              for (let j = 0; j < res.data.wxapp_suborder_set.length; j++) {    
                list[j] = res.data.wxapp_suborder_set[j].item_sku;
              }
              for (let i = 0; i <wx.getStorageSync('shopCarInfo').shopList.length;i++){
                //console.log(wx.getStorageSync('shopCarInfo').shopList[i].propertyChildIds)
                let id = wx.getStorageSync('shopCarInfo').shopList[i].propertyChildIds;  
                  if (list.indexOf(id)==-1 && id !=null){
                    shopCarInfo_list[num] = wx.getStorageSync('shopCarInfo').shopList[i];
                    //console.log(shopCarInfo_list[num]);
                    num++;
                  }    
              }
              shopCarInfo_dis = { "shopList": shopCarInfo_list,"shopNum":num};
              wx.setStorageSync('shopCarInfo', shopCarInfo_dis);
            }
            
            if (!e) {
              that.setData({
                //totalScoreToPay: res.data.data.score,    
                //isNeedLogistics: res.data.data.isNeedLogistics, //是否需要物流信息
                //allGoodsPrice: res.data.data.amountTotle,  //总物品价格
                //allGoodsAndYunPrice: res.data.data.amountLogistics + res.data.data.amountTotle, //物品价格和运费
                //yunPrice: res.data.data.amountLogistics  //运费
                allGoodsPrice: res.data.pay_fee,
                yunPrice: res.data.post_fee,
                allGoodsAndYunPrice: res.data.pay_fee + res.data.post_fee,
              });
              // that.getMyCoupons();
              //console.log(allGoodsAndYunPrice)
              return;
            }
            
            // 配置模板消息推送
            var postJsonString = {};
            var allGoodsAndYunPrice = res.data.pay_fee + res.data.post_fee;
            if (that.data.orderType=="buyNow"){
              var allGoodsAndYunPrice = that.data.pingtuanprice + res.data.post_fee;
            }
            postJsonString.keyword1 = {
              // value: res.data.data.dateAdd,
              value: res.data.created_on,
              color: '#173177'
            }
            postJsonString.keyword2 = {
              //value: res.data.data.amountReal + '元',
              value: allGoodsAndYunPrice + '元',
              color: '#173177'
            }
            postJsonString.keyword3 = {
              //value: res.data.data.orderNumber,
              value: res.data.order_no,
              color: '#173177'
            }
            postJsonString.keyword4 = {
              value: '订单已关闭',
              color: '#173177'
            }
            postJsonString.keyword5 = {
              value: '您可以重新下单，请在30分钟内完成支付',
              color: '#173177'
            }
            app.sendTempleMsg(res.data.pk, -1,
              'mGVFc31MYNMoR9Z-A9yeVVYLIVGphUVcK2-S2UdZHmg', e.detail.formId,
              'pages/index/index', JSON.stringify(postJsonString));
            postJsonString = {};
            postJsonString.keyword1 = {
              value: '您的订单已发货，请注意查收',
              color: '#173177'
            }
            postJsonString.keyword2 = {
              //value: res.data.data.orderNumber,
              value: res.data.order_no,
              color: '#173177'
            }
            postJsonString.keyword3 = {
              //value: res.data.data.dateAdd,
              value: res.data.created_on,
              color: '#173177'
            }
            // app.sendTempleMsg(res.data.pk, 2,
            //   'Arm2aS1rsklRuJSrfz-QVoyUzLVmU2vEMn_HgMxuegw', e.detail.formId,
            //   'pages/order-details/index?id=' + res.data.pk, JSON.stringify(postJsonString));
            // 下单成功，跳转到订单管理界面
            if(ispingtuan){
              wx.redirectTo({
                url: "/pages/pintuan/index"
              });
            }
            wx.redirectTo({
              url: "/pages/order-list/index"
            });
          }
          
        })
    
    // //调用拼团接口拼团  
    // if (ispingtuan) {
    //   if (is_commander) {
    //     //调用团长接口
    //     wx.request({
    //       url: app.globalData.domain + '/wxapp/bulk_purchase/',
    //       header: {
    //         'Authorization': 'JWT ' + wx.getStorageSync('token')
    //       },
    //       method: "POST",
    //       data: {
    //         ispingtuan: ispingtuan,
    //         wxapp_suborder_set: this.data.item_sku_list,
    //         consignee: that.data.curAddressData.pk,
    //         coupon_list: that.data.curCoupon_list,
    //         user_mem: remark,
    //         order_status: order_status,
    //         is_commander: ispingtuan == true ? is_commander : '',
    //         order:244,
    //         item: that.data.goodsList[0].goodsId,
    //         bulk_purchase_tpl: that.data.pin_tuan_tpl
    //       },
    //       success: (res) => {
    //         wx.redirectTo({
    //           url: "/pages/pintuan/index"
    //         });
    //       },
    //     })
    //   } else {
    //     //调用团员接口

    //     wx.request({
    //       url: app.globalData.domain + '/wxapp/sub_bulk_purchase/',
    //       header: {
    //         'Authorization': 'JWT ' + wx.getStorageSync('token')
    //       },
    //       method: "POST",
    //       data: {
    //         order: res.data.pk,
    //         wx_app_bulk_purchase: that.data.pingtuanOpenId
    //       },
    //       success: (res) => {
    //         wx.redirectTo({
    //           url: "/pages/pintuan/index"
    //         });
    //       }
    //     })
    //   }
    // }
  },
  initShippingAddress: function() {
    var that = this;
    wx.request({
      //url: 'https://api.it120.cc/' + app.globalData.subDomain + '/user/shipping-address/default',
      url: app.globalData.domain + '/wxapp/consignee/',
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      data: {
        is_default: 'True',
      },
      success: (res) =>{
        //if (res.data.code == 0) {
        if (res.statusCode == 200) {
          that.setData({
            curAddressData:res.data[0]
            // curAddressData: res.data.data
          });
        } else {
          that.setData({
            curAddressData: null
          });
        }
        that.getMyCoupons();

        // that.processYunfei();
      }
    })
  },
  processYunfei: function() {
    var that = this;
    var goodsList = this.data.goodsList;
    var goodsJsonStr = "[";
    var isNeedLogistics = 0;
    var allGoodsPrice = 0;

    for (let i = 0; i < goodsList.length; i++) {
      let carShopBean = goodsList[i];
      if (carShopBean.logistics) {
        isNeedLogistics = 1;
      }
      allGoodsPrice += carShopBean.price * carShopBean.number;

      var goodsJsonStrTmp = '';
      if (i > 0) {
        goodsJsonStrTmp = ",";
      }


      let inviter_id = 0;
      let inviter_id_storge = wx.getStorageSync('inviter_id_' + carShopBean.goodsId);
      if (inviter_id_storge) {
        inviter_id = inviter_id_storge;
      }


      goodsJsonStrTmp += '{"goodsId":' + carShopBean.goodsId + ',"number":' + carShopBean.number + ',"propertyChildIds":"' + carShopBean.propertyChildIds + '","logisticsType":0, "inviter_id":' + inviter_id + '}';
      goodsJsonStr += goodsJsonStrTmp;


    }
    goodsJsonStr += "]";
    //console.log(goodsJsonStr);
    that.setData({
      isNeedLogistics: isNeedLogistics,
      goodsJsonStr: goodsJsonStr
    });
    that.createOrder();
  },
  addAddress: function() {
    wx.navigateTo({
      url: "/pages/address-add/index"
    })
  },
  selectAddress: function() {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },
  getMyCoupons: function() {
    var that = this;
    wx.request({
      url: app.globalData.domain + '/wxapp/coupon/',
      data: {
        // token: wx.getStorageSync('token'),
        // status: 0
      },
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      success: function(res) {
       
        //if (res.data.code == 0) {
        if (res.statusCode == 200){
          var coupons = res.data.filter(entity => {
            return entity.min_origin_fee <= that.data.allGoodsAndYunPrice;
          });
          if (coupons.length > 0) {
            that.setData({
              hasNoCoupons: false,
              coupons: coupons
            });
          }
        }
      }
    })
  },
  bindChangeCoupon: function(e) {
    const selIndex = e.detail.value[0] - 1;
    if (selIndex == -1) {
      this.setData({
        youhuijine: 0,
        curCoupon: null
      });
      return;
    }
    //console.log("selIndex:" + selIndex);
    this.setData({
      // youhuijine: this.data.coupons[selIndex].money,
      youhuijine: this.data.coupons[selIndex].denominations,
      curCoupon: this.data.coupons[selIndex]
    });
  }
})